﻿using System;
using System.Collections.Generic;
using System.Linq;

using DreamCube.Websites.EasyUIModel;
using DreamCube.Framework.DataAccess.Basic;
using DreamCube.Foundation.Serialization;
using DreamCube.Foundation.Basic.Utility;

namespace DreamCube.Websites.BLL
{
    public static class ArchiveSystemHelper
    {
        #region "方法"

        /// <summary>
        /// 缓存每一个管理系统所有的分类
        /// </summary>
        private static Dictionary<Int32, ArchiveClass[]> systemClass = new Dictionary<Int32, ArchiveClass[]>();

        /// <summary>
        /// 缓存每一个管理系统所有的分类(JSON格式数据)
        /// </summary>
        private static Dictionary<Int32, String> systemClassEasyJSON = new Dictionary<Int32, String>();

        #endregion

        /// <summary>
        /// 获取管理系统的所有分类的JSON节点数据（适用于EasyUI的tree控件）
        /// </summary>
        /// <param name="systemID">系统的ID号</param>
        /// <returns></returns>
        public static String GetSystemAllClassEasyUIJSON(Int32 systemID)
        {
            String json = null;
            if (systemClassEasyJSON.TryGetValue(systemID, out json) && !MyWebsite.IsLocalhostWeb())
            {
                return json;
            }
            else
            {
                ArchiveClass[] classList = GetSystemAllClass(systemID);
                if (classList == null) return "";
                //借助堆栈来创建递归的数据
                Queue<ArchiveClass> queue = new Queue<ArchiveClass>();
                List<TreeNode> treeList = new List<TreeNode>();
                //选中所有的父节点（并且按orderinde的升序进行排序）
                IEnumerable<ArchiveClass> parentList = classList.Where<ArchiveClass>((m) =>
                {
                    return m.ParentID == 0;
                }).OrderBy(module => module.OrderIndex);

                //组装成所有父与子的对应关系
                foreach (ArchiveClass m in parentList)
                {
                    queue.Enqueue(m);
                }

                while (queue.Count > 0)
                {
                    //出栈
                    ArchiveClass m = queue.Dequeue();
                    //先添加到集合中
                    TreeNode tree = new TreeNode()
                    {
                        Checked = false,
                        Text = m.Title,
                        ID = m.ID
                    };
                    Int32 i = 0;
                    for (; i < treeList.Count; i++)
                    {
                        if (treeList[i].ID == tree.ID)
                        {
                            treeList[i].ChildrenNode.Add(tree);
                            break;
                        }
                    }
                    //如果找不到父节点，则以父节点的方式添加到列表中
                    if (i == treeList.Count) treeList.Add(tree);
                    //再处理子分类
                    IEnumerable<ArchiveClass> subClass = parentList.Where<ArchiveClass>((child) =>
                    {
                        return child.ParentID == m.ID;
                    }).OrderBy(module => module.OrderIndex);
                    //先清空数据，因为这个模块对象是静态全局共享的
                    m.SubClass.Clear();
                    foreach (ArchiveClass sub in subClass)
                    {
                        queue.Enqueue(sub);
                    }
                }
                json =  MyJson.Serialize(treeList);
                //添加到缓存中
                MyDictionary.TryAdd(systemClassEasyJSON, systemID, json, Foundation.Basic.Enums.CollectionsAddOper.ReplaceIfExist);
                return json;
            }
        }

        /// <summary>
        /// 获取管理系统的所有分类
        /// </summary>
        /// <param name="systemID">系统的ID号</param>
        /// <returns></returns>
        public static String GetSystemAllClassJSON(Int32 systemID)
        {
            ArchiveClass[] classList = GetSystemAllClass(systemID);
            return MyJson.Serialize(classList);
        }

        /// <summary>
        /// 获取管理系统的所有分类
        /// </summary>
        /// <param name="systemID">系统的ID号</param>
        /// <returns></returns>
        public static ArchiveClass[] GetSystemAllClass(Int32 systemID)
        {
            ArchiveClass[] archiveClass = null;
            if (systemClass.TryGetValue(systemID, out archiveClass) && !MyWebsite.IsLocalhostWeb())
                return archiveClass;
            else
            {
                Database db = WebSession.CurrentSystem.GetDB();
                List<ArchiveClass> classList = db.GetModelList<ArchiveClass>(ArchiveClass.TableName, "*", "");
                if (classList == null) return null;
                //选中所有的父节点（并且按orderinde的升序进行排序）
                IEnumerable<ArchiveClass> parentList = classList.Where<ArchiveClass>((m) =>
                {
                    return m.ParentID == 0;
                }).OrderBy(module => module.OrderIndex);
                //组装成所有父与子的对应关系
                foreach (ArchiveClass m in parentList)
                {
                    IEnumerable<ArchiveClass> subClass = parentList.Where<ArchiveClass>((child) =>
                    {
                        return child.ParentID == m.ID;
                    }).OrderBy(module => module.OrderIndex);
                    m.SubClass.Clear();//先清空数据，因为这个模块对象是静态全局共享的
                    foreach (ArchiveClass sub in subClass)
                    {
                        //if (!m.ChildModules.Contains(child)) 
                        m.SubClass.Add(sub);
                    }
                }
                archiveClass = parentList.ToArray<ArchiveClass>();
                MyDictionary.TryAdd(systemClass, systemID, archiveClass, Foundation.Basic.Enums.CollectionsAddOper.ReplaceIfExist);
                return archiveClass;
            }
        }

        /// <summary>
        /// 获取管理系统的顶级类目
        /// </summary>
        /// <param name="systemID">系统的ID号</param>
        /// <returns></returns>
        public static List<ArchiveClass> GetSystemTopClass(Int32 systemID)
        {
            //List<ArchiveClass> classList = db.get
            throw new NotImplementedException();
        }
    }
}
